package bi.example.demo9;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "jdbc:mysql://localhost:3306/studentdb?serverTimezone=UTC";
        String dbUser = "root";
        String dbPass = "123456";
        String user_id = request.getParameter("user_id");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        Connection conn = null;
        PreparedStatement prep = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, dbUser, dbPass);
            String sql = "SELECT * FROM users WHERE user_id = ? AND password = ? AND role = ?";
            prep = conn.prepareStatement(sql);
            prep.setString(1, user_id);
            prep.setString(2, password);
            prep.setString(3, role);
            rs = prep.executeQuery();

            if (rs.next()) {
                HttpSession session = request.getSession();
                session.setAttribute("user_id", user_id);
                if ("student".equals(role)) {
                    response.sendRedirect("index.jsp");
                } else if ("teacher".equals(role)) {
                    response.sendRedirect("index_teacher.jsp");
                } else if ("admin".equals(role)) {
                    response.sendRedirect("index_Manager.jsp");
                }
            } else {
                response.getWriter().println("用户名或密码错误！");
            }
        } catch (SQLException se) {
            se.printStackTrace();
            response.getWriter().println("数据库连接错误！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            response.getWriter().println("JDBC驱动加载失败！");
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException se2) {

            }
            try {
                if (prep != null) prep.close();
            } catch (SQLException se) {

            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}